package com.base.test.mysql2es.model;

import com.base.test.mysql2es.util.CollectionUtil;
import com.base.test.mysql2es.util.ObjectUtil;
import lombok.Getter;
import lombok.Setter;

import java.util.List;

@Getter
@Setter
public class ChildMapping {

    private String mainField;

    private String sql;

    private String childField;


    public void check(String nested) {
        ObjectUtil.assertNil(mainField, "必须设置子表(" + nested + "): main-field");
        ObjectUtil.assertNil(sql, "必须设置子表(" + nested + "): sql");
        ObjectUtil.assertNil(childField, "必须设置子表(" + nested + "): nested-field");
    }
    public String nestedQuerySql(List<Object> relations) {
        if (ObjectUtil.isBlank(mainField) || ObjectUtil.isBlank(sql) || ObjectUtil.isBlank(childField) || CollectionUtil.isEmpty(relations)) {
            return ObjectUtil.EMPTY;
        }

        StringBuilder sbd = new StringBuilder();
        boolean hasQueryRelationInSql = false;
        for (String s : sql.split(" ")) {
            for (String s1 : s.split(",")) {
                if (s1.trim().equals(childField.trim())) {
                    hasQueryRelationInSql = true;
                    break;
                }
            }
        }
        if (hasQueryRelationInSql) {
            sbd.append(sql.trim());
        } else {
            sbd.append(sql.trim().replaceFirst("^(?i)SELECT ", "SELECT " + childField + ", "));
        }
        sbd.append(" WHERE ").append(childField);
        Object relation = CollectionUtil.first(relations);
        if (relations.size() == 1) {
            sbd.append(" = ");

            if (ObjectUtil.isNumber(relation)) {
                sbd.append(relation);
            } else {
                sbd.append("'").append(relation).append("'");
            }
        } else {
            sbd.append(" IN (");
            boolean hasNumber = ObjectUtil.isNumber(relation);
            for (int i = 0; i < relations.size(); i++) {
                if (i > 0) {
                    sbd.append(",");
                }
                Object r = relations.get(i);
                if (hasNumber) {
                    sbd.append(r);
                } else {
                    sbd.append("'").append(r).append("'");
                }
            }
            sbd.append(")");
        }
        return sbd.toString();
    }
}
